package com.coupon.constrol;

import com.coupon.pojo.*;
import com.coupon.service.UserService;
import com.coupon.util.JsonResult;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * @author :wn
 * @program : coupon
 * @descript : 用户控制器
 * @create :2020-12-30 16:56
 */



@Controller
@ResponseBody
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;


    @RequestMapping("/login")
    public Map login(@RequestParam("phone") String phone) {
        User login = userService.login(phone);
        //登录的状态（1/0）
        JsonResult jsonResult = new JsonResult();
        if (login != null) {
            //登录成功
            jsonResult.setCode(1);
            //获取用户的详情
            jsonResult.setData(login);
        } else {
            jsonResult.setCode(0);
        }
        return jsonResult.getValues();

    }
    @PostMapping("/reg") //直接指定请求类型为post方法
    @ResponseBody
    public String reg(@RequestParam("name") String name, @RequestParam("phone") String phone,
                      @RequestParam("captcha") String captcha, HttpSession session) {

        String code = (String) session.getAttribute("code");
        JsonResult jsonResult = new JsonResult();
        if (code.equals(captcha)) {
            //必须让验证码相同，才能执行注册操作。
            User user = new User();
            user.setName(name);
            user.setPhone(phone);
            user.setRegTime(new Date());
            Boolean register = userService.register(user);
            if (register) {

                jsonResult.setCode(1);

                System.out.println("注册成功！");

            } else {
                jsonResult.setCode(0);

                System.out.println("注册失败，该手机已经注册过会员");
            }
        } else {

            System.out.println("验证码错误");

            jsonResult.setCode(0);
        }
        return jsonResult.getValues().toString();

    }

    @RequestMapping("/getList")
    @ResponseBody
    public Map<String, Object> getList(@RequestParam("page") int page, @RequestParam(value = "name", required = false)String name) {
        PageObject all =  userService.findAll(page, name);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode(1);
        jsonResult.setData(all.getDataList());
        //前端在分页的时候，需要判断count值
        jsonResult.put("count", all.getCount());
        return jsonResult.getValues();
    }

    @RequestMapping("/exportList")
    public void exportList(HttpServletResponse response) throws IOException, ParseException {

        PageObject all = userService.findAll(null,null);
        List<User> dataList = all.getDataList();
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet getSheet = workbook.createSheet("注册会员信息表");
        String[] headers = { "序号", "姓名", "电话号码","注册时间"};
        HSSFRow row = getSheet.createRow(0);
        for(int i=0;i<headers.length;i++){
            HSSFCell cell = row.createCell(i);
            cell.setCellValue(headers[i]);
        }
        int rowNum = 1;
        for (User u : dataList) {
            HSSFRow dataRow = getSheet.createRow(rowNum);

            dataRow.createCell(0).setCellValue(rowNum);
            dataRow.createCell(1).setCellValue(u.getName());
            dataRow.createCell(2).setCellValue(u.getPhone());
            dataRow.createCell(3).setCellValue(u.getRegTime());
            rowNum++;
        }


        String fileName = "注册会员信息表.xls";
        fileName = URLEncoder.encode(fileName,"utf-8").replaceAll("\\+", "%20");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.flushBuffer();
        workbook.write(response.getOutputStream());
    }

    @RequestMapping("/getCpn")
    @ResponseBody
    public Map getCpn(@RequestParam("cpId")Integer id,@RequestParam("phone")String phone){

        Date date=new Date();
        UserGet userGet=new UserGet();
        userGet.setCpId(id);
        userGet.setPhone(phone);
        userGet.setDatetime(date);
        int cpn = userService.getCpn(userGet);
        JsonResult jsonResult=new JsonResult();
        if(cpn>0){
            jsonResult.setCode(1);
        }else {
            jsonResult.setCode(0);
        }
        return jsonResult.getValues();
    }
    @RequestMapping("/getCpnList")
    @ResponseBody
    public Map getCpnList(@RequestParam(value = "page",required = false)Integer page,@RequestParam(value = "phone",required = true)String phone){
        PageObject pageObject = userService.selectAllUserGet(page,phone);
        List<CouponList> dataList = pageObject.getDataList();
        JsonResult jsonResult=new JsonResult();
        jsonResult.setData(dataList);
        jsonResult.setCode(1);
        return jsonResult.getValues();
        }

        @RequestMapping("/exportCpnUsedList")
        public void exportCpnUsedList(@RequestParam(value = "from" ,required = false)String  from,@RequestParam(value = "to",required = false)String to,HttpServletResponse response) throws IOException {

            PageObject<ExchangeCoupon> pageObject = userService.selectUsedList(from,to);
            List<ExchangeCoupon> dataList = pageObject.getDataList();


            HSSFWorkbook workbook = new HSSFWorkbook();

            HSSFSheet getSheet = workbook.createSheet("注册会员信息表");
            // headers表示excel表中第一行的表头 在excel表中添加表头
            String[] headers = { "序号", "姓名", "电话号码","优惠卷名称","兑换时间"};
            // 创建第一行(表头)
            HSSFRow row = getSheet.createRow(0);
            for(int i=0;i<headers.length;i++){
                HSSFCell cell = row.createCell(i);
                cell.setCellValue(headers[i]);
            }

            // 数据行
            int rowNum = 1;
           for(ExchangeCoupon u:dataList) {
                HSSFRow dataRow = getSheet.createRow(rowNum);

                dataRow.createCell(0).setCellValue(rowNum);
                dataRow.createCell(1).setCellValue(u.getUserName());
                dataRow.createCell(2).setCellValue(u.getPhone());
                dataRow.createCell(3).setCellValue(u.getCpName());
                dataRow.createCell(4).setCellValue(u.getUseTime());

                rowNum++;
            }

            // 设置文件名:
            String fileName = "优惠券使用情况.xls";
            // 对于文件名中的中文进行处理
            fileName = URLEncoder.encode(fileName,"utf-8").replaceAll("\\+", "%20");

            //返回给前端下载
            //通知浏览器，此次响应内容不应该用访问访问，而应该用下载方式
            response.setContentType("application/octet-stream");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            response.flushBuffer();
            workbook.write(response.getOutputStream());

        }
        @RequestMapping("/getCpnListForWeb")
        @ResponseBody
     public Map getCpnListForWeb(@RequestParam("phone")String phone){
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date=new Date();
            String format = simpleDateFormat.format(date);
            PageObject<Coupon> pageObject = userService.hadGetCoupon(phone, format);
            PageObject<Coupon> pageObject1 = userService.notGetCoupon(phone, format);
            PageObject<Coupon> pageObject2 = userService.outTimeCoupon(phone, format);
            JsonResult jsonResult=new JsonResult();
            jsonResult.put("userNotGetCpnList",pageObject1.getDataList());
            jsonResult.put("userGetCpnList",pageObject.getDataList());
            jsonResult.put("overExpire",pageObject2.getDataList());
            return jsonResult.getValues();
        }

        @RequestMapping("/useCpn")
        public Map userCpn(@RequestParam("cpId") int cpId,@RequestParam("phone")String phone){
            int i = userService.writeOff(cpId, phone);
            JsonResult jsonResult=new JsonResult();
            if(i>0){
                jsonResult.setCode(1);
            }else{
                jsonResult.setCode(0);
            }
            return jsonResult.getValues();
        }

        @RequestMapping("/cpnListForWeb")
       public Map cpnListForWeb(@RequestParam("phone")String phone){
            PageObject pageObject = userService.selectUserGet(phone);
            PageObject pageObject1 = userService.overExpireCpn(phone);

            JsonResult jsonResult=new JsonResult();
            jsonResult.put("userGetCpnIsUsedList",pageObject.getDataList());
            jsonResult.put("overExpire",pageObject1.getDataList());
        return jsonResult.getValues();
        }

        @RequestMapping("/getCpnUsedList")
        public Map getCpnUsedList(@RequestParam("page") Integer page, @RequestParam(value = "from",required = false)
                String  from, @RequestParam(value = "to",required = false) String  to){
            PageObject pageObject = userService.selectExchangeList(page, from, to);
            List dataList = pageObject.getDataList();
            JsonResult jsonResult=new JsonResult();
            jsonResult.setData(dataList);
            jsonResult.setCode(1);
            return jsonResult.getValues();
        }



}
